<template>
	<view>
		<z-paging ref="paging" v-model="dataList" @query="queryList">
			<template #top>
				<tn-navbar>停车支付查询</tn-navbar>
				<tn-input v-model="inputValue" placeholder="请输入车牌查询" @change="filterData">
					<template #suffix>
						<view class="tn-ml tn-mr" @click="filterData"><tn-icon name="search" color=" tn-gray_bg"></tn-icon></view>
					</template>
				</tn-input>
				<view class="tn-shadow  ">
					<view class="tn-flex tn-mt-sm justify-end tn-pr-sm  tn-pb-sm ">
						<view class="tn-flex tn-blue_text" @click="openEditPopup">
							<tn-icon name="filter"></tn-icon>
							筛选
						</view>
					</view>
				</view>
			</template>
			<!-- 停车支付查询的内容 -->
			<view class="list">
				<view class="  " v-for="(item, index) in dataList" :key="index" @click="tnParamById('/pages/main/common/detail', JSON.stringify(item))">
					<view class="    tn-shadow-md tn-p-xs tn-m-sm tn-radius">
						<view class="tn-flex justify-between tn-p-xs ">
							<view class="tn-flex  ">
								<tn-icon name="bankcard" size="40"></tn-icon>
								<text class="tn-pl-sm tn-text-bold  ">{{ item.numberPlate }}</text>
							</view>

							<view class="tn-flex  ">
								<tn-title v-if="item.inTime == 0" class="tn-mr-xs " title="异常出场" mode="dot" assist-color="tn-teal-dark" color="tn-teal-dark" />
								<tn-title v-if="item.outTime == 0" class="tn-mr-xs " title="已进场" mode="dot" assist-color="tn-teal-dark" color="tn-teal-dark" />
								<tn-title v-if="item.payTime == 0" class="tn-mr-xs " title="待支付" mode="dot" assist-color="tn-orange-dark" color="tn-orange-dark" />
								<tn-title
									v-if="item.outTime > 0 && item.payTime > 0"
									class="tn-mr-xs "
									title="已出场"
									mode="dot"
									assist-color="tn-gray-dark"
									color="tn-gray-dark"
								/>
							</view>
						</view>
						<view class=" tn-m-xs tn-border-top tn-border-dashed tn-grey-disabled_border"></view>
						<view class="  tn-mt-xs tn-p-sm tn-text-center tn-text-sm   ">
							<view class="tn-flex justify-between   tn-pt-sm">
								<view class=" ">
									<text>入场时间:</text>
									<text class="tn-ml-xs  tn-grey_text">{{ item.newInTime }}</text>
								</view>
								<view class=" tn-text-sm ">
									<text>预计金额:</text>
									<text class="tn-orangered_text">￥{{ item.amountsPayable }}</text>
								</view>
							</view>
							<view class="tn-flex justify-between   tn-pt-sm">
								<view class="">
									<text>离场时间:</text>
									<text class="tn-ml-xs tn-grey_text">{{ item.newOutTime }}</text>
								</view>
								<view class="">
									<text>实付金额:</text>
									<text class=" tn-orangered_text">￥{{ item.amountActuallyPaid }}</text>
								</view>
							</view>
							<view class="tn-flex justify-between   tn-pt-sm">
								<view class="">
									<text>时长:</text>
									<text class="tn-ml-xs tn-grey_text">{{ item.parkingDuration }}</text>
								</view>
								<view class="">
									<text>车类:</text>
									<text class=" tn-orangered_text">{{ item.newCarType }}</text>
								</view>
							</view>
							<view class="tn-flex justify-between items-center tn-text-sm tn-pt-sm">
								<view class="tn-flex-4">
									<text>{{ item.paymentAgencyShortNameTitle }}</text>
								</view>

								<view>
									<tn-button @click="contactDriver(item)" plain border-color="tn-teal-dark" text-color="tn-teal-dark">
										<text class="tn-text-bold">联系车主</text>
									</tn-button>
								</view>
								<view>
									<tn-button @click="confirmEdit" bg-color="tn-teal-dark" text-color="tn-white"><text class="tn-text-bold">入场视频</text></tn-button>
								</view>
								<view>
									<tn-button @click="confirmEdit" bg-color="tn-teal-dark" text-color="tn-white"><text class="tn-text-bold">出场视频</text></tn-button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<template #loadingMoreNoMore></template>
		</z-paging>

		<tn-popup v-model="isPopupVisible" width="80%" top="230rpx" open-direction="top" :overlay="false" :radius="25">
			<view class="tn-shadow  tn-p-sm  tn-border  tn-border-bottom  tn-border-top tn-gray-disabled_border">
				<tn-form ref="formRef" :model="formData" label-position="top">
					<tn-form-item label="入场时间">
						<view class="tn-flex justify-between">
							<view>
								<tn-input @focus="openPickerDate('minInTime')" :model-value="formData.minInTime" placeholder="入场时间>=">
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('minInTime')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
							-
							<view>
								<tn-input @focus="openPickerDate('maxInTime')" :model-value="formData.maxInTime" placeholder="入场时间<=">
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('maxInTime')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
						</view>
					</tn-form-item>
					<tn-form-item label="出场时间">
						<view class="tn-flex justify-between">
							<view>
								<tn-input @focus="openPickerDate('minOutTime')" :model-value="formData.minOutTime" placeholder="出场时间>=">
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('minOutTime')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
							-
							<view>
								<tn-input @focus="openPickerDate('maxOutTime')" :model-value="formData.maxOutTime" placeholder="出场时间<=">
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('maxOutTime')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
						</view>
					</tn-form-item>
					<tn-form-item label="进出场通道">
						<view class="tn-flex justify-between">
							<view>
								<tn-input
									@focus="openPicker('inCheckPointList')"
									:model-value="selectOptions.checkPointLabel[formData.inCheckPointId]"
									placeholder="请选择入场通道"
								>
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('inCheckPointId')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
							<view>
								<tn-input
									@focus="openPicker('outCheckPointList')"
									:model-value="selectOptions.checkPointLabel[formData.outCheckPointId]"
									placeholder="请选择出场通道"
								>
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('outCheckPointId')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
						</view>
					</tn-form-item>

					<tn-form-item label="进出场方式">
						<view class="tn-flex justify-between">
							<view>
								<tn-input
									@focus="openPicker('inReleaseTypeList')"
									:model-value="selectOptions.inReleaseTypeLabel[formData.inReleaseType]"
									placeholder="请选择入场方式"
								>
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('inReleaseType')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
							<view>
								<tn-input
									@focus="openPicker('outReleaseTypeList')"
									:model-value="selectOptions.outReleaseTypeLabel[formData.outReleaseType]"
									placeholder="请选择出场方式"
								>
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('outReleaseType')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
						</view>
					</tn-form-item>

					<tn-form-item label="车辆类型">
						<view class="tn-flex justify-between">
							<view>
								<tn-input @focus="openPicker('carTypeList')" :model-value="selectOptions.carTypeLabel[formData.carType]" placeholder="请选择车辆类型">
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('carType')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
							<view>
								<tn-input
									@focus="openPicker('paymentAgencyList')"
									:model-value="selectOptions.paymentAgencyLabel[formData.paymentAgencyShortName]"
									placeholder="请选择支付方式"
								>
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('paymentAgencyShortName')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
						</view>
					</tn-form-item>

					<tn-form-item label="家庭组/一多位多车">
						<view class="tn-flex justify-between">
							<view>
								<tn-input v-model="formData.homeGroup" placeholder="家庭组/一多位多车">
									<template #suffix>
										<view class="tn-ml tn-mr" @click="cleanInputValue('homeGroup')"><tn-icon name="delete" color=" tn-gray_bg"></tn-icon></view>
									</template>
								</tn-input>
							</view>
						</view>
					</tn-form-item>
				</tn-form>

				<view class="tn-mt tn-flex justify-evenly  ">
					<tn-button
						@click="closePopup"
						text-color="tn-white"
						bg-color="tn-grey_bg
"
					>
						取消
					</tn-button>
					<tn-button @click="confirmEdit" text-color="tn-white">确认</tn-button>
				</view>
			</view>
		</tn-popup>
		<!-- 时间选择器 -->
		<tn-date-time-picker v-model:open="openPickerDateVisible" mode="datetime" @confirm="confirmPickerDate" @close="closePickerDate" />
		<!-- 字典选择器 -->
		<tn-picker v-model:open="openPickerVisible" :data="pickerData" @confirm="confirmPicker" @close="closePicker" />
	</view>
</template>

<script setup lang="ts">
import {onMounted, type Ref, ref} from 'vue';
import dayjs from "dayjs";
import CfCarParkUtil from "@/cfsheep/api/cfCarPark/park";
import {parseTime, timeFn} from "@/cfsheep/util";
import CfPayUtil from "@/cfsheep/api/pay/pay";
import CfIOTUtil from "@/cfsheep/api/iot/iot";
import {onLoad} from "@dcloudio/uni-app";
import {tnParamById} from "@/utils/tnUtil";
	// ===============模拟数据 =========================

	// 模拟数据
	const tempList = ref([]);

	// z-paging 示例
  const carParkId = ref(0);
  const numberPlate = ref('');
  const carTypeList = ref([]);
  const paymentAgencyList = ref([]);

  const formData = ref({
    minInTime: null,
    maxInTime: null,
    minOutTime: null,
    maxOutTime: null,
    inCheckPointId:null,
    outCheckPointId:null,
    carType:null,
    inReleaseType:null,
    outReleaseType:null,
    homeGroup:null,
    paymentAgencyShortName:null,
  });

  // 下拉筛选- 筛选索引
  const isPopupVisible = ref(false);
  const openEditPopup = (value : any) => {
    isPopupVisible.value = true;
  };

  const closePopup = () => {
    isPopupVisible.value = false;
  };
  const confirmEdit = () => {
    // 确认修改逻辑
    closePopup();
    queryList(1, 10);
  };
  const contactDriver = async (useLog: CfCarParkUseLog) => {
	     console.log('成功获取到手机号1', useLog.uid);
    if(useLog.uid==null || useLog.uid==0){
      return;
    }
    const _phone = await CfCarParkUtil.getCarParkUseLogDriverPhone({
      id: useLog.id
    });
    if (_phone.code == 10002) {

      console.log('成功获取到手机号', _phone.data);
	  uni.makePhoneCall({
	    phoneNumber: _phone.data,
	  });
    }
 
  };


  // 日期时间筛选-选择器key
  const pickerDateKey = ref('');

  // 日期时间控制选择器的可见性
  const openPickerDateVisible = ref(false);

  // 打开日期时间选择器
  const openPickerDate = (type: any) => {
    pickerDateKey.value = type;
    openPickerDateVisible.value = true; // 显示选择器
  };

  // 关闭日期时间选择器
  const closePickerDate = () => {
    openPickerDateVisible.value = false; // 隐藏选择器
  };

  // 确认日期时间选择器的选择
  const confirmPickerDate = (value : any) => {
    formData.value[pickerDateKey.value] = value;
    closePickerDate(); // 关闭选择器
  };

  const filterData = (_numberPlate : string) => {
    if (_numberPlate.length >= 4 || _numberPlate === '') {
      numberPlate.value = _numberPlate;
      queryList(1, 10);
    } else {
      dataList.value = [];
      paging.value.complete(dataList.value);
    }
  };
  // z-paging 示例
  const paging = ref(null);
  // 数据列表
  const dataList: Ref<CfCarParkUseLog[]> = ref([]);

  const releaseTypeArr = [
    { value: 0, label: '未放行' },
    { value: 1, label: '自动抬杆' },
    { value: 2, label: '人工抬杆' },
    { value: 3, label: '手机放行' },
    { value: 4, label: '扫码' },
    { value: 5, label: '异常放行' },
  ];

  //下拉框数据
  const selectOptions = ref({
    dict: {
      inCheckPointList: [],
      outCheckPointList: [],
      carTypeList: [],
      paymentAgencyList: [],
      //0-未放行/1-自动抬杆/2-人工抬杆/3-手机放行，断电断网时/4-扫码入场/5-异常放行
      inReleaseTypeList: [
        { label: "未放行", text: "未放行", value: 0 },
        { label: "自动抬杆", text: "自动抬杆", value: 1 },
        { label: "人工抬杆", text: "人工抬杆", value: 2 },
        { label: "手机放行", text: "手机放行", value: 3 },
        { label: "扫码入场", text: "扫码入场", value: 4 },
        { label: "异常放行", text: "异常放行", value: 5 }
      ],
      outReleaseTypeList: [
        { label: "未放行", text: "未放行", value: 0 },
        { label: "自动抬杆", text: "自动抬杆", value: 1 },
        { label: "人工抬杆", text: "人工抬杆", value: 2 },
        { label: "手机放行", text: "手机放行", value: 3 },
        { label: "扫码入场", text: "扫码入场", value: 4 },
        { label: "异常放行", text: "异常放行", value: 5 }
      ],
    },
    checkPointLabel: {},
    carTypeLabel: {},
    paymentAgencyLabel: {},
    inReleaseTypeLabel: {0: '未放行', 1: '自动抬杆', 2: '人工抬杆', 3: '手机放行', 4: '扫码入场', 5: '异常放行'},
    outReleaseTypeLabel: {0: '未放行', 1: '自动抬杆', 2: '人工抬杆', 3: '手机放行', 4: '扫码入场', 5: '异常放行'},
  });

  // 选择器key
  const pickerKey = ref('');
  // 选择器数据
  const pickerData = ref([]);

  // 控制选择器的可见性
  const openPickerVisible = ref(false);

  // 打开选择器
  const openPicker = (type:any)  => {
    pickerKey.value = type;
    pickerData.value = selectOptions.value.dict[type];
    openPickerVisible.value = true; // 显示选择器
  };

  // 关闭选择器
  const closePicker = () => {
    openPickerVisible.value = false; // 隐藏选择器
  };

  const cleanInputValue = (valueType: string) => {
    formData.value[valueType] = null;
  };

  // 确认选择器的选择
  const confirmPicker = (value: any) => {
    switch (pickerKey.value){
      case "inCheckPointList":
        formData.value.inCheckPointId = value;
        break;
      case "outCheckPointList":
        formData.value.outCheckPointId = value;
        break;
      case "inReleaseTypeList":
        formData.value.inReleaseType = value;
        break;
      case "outReleaseTypeList":
        formData.value.outReleaseType = value;
        break;
      case "carTypeList":
        formData.value.carType = value;
        break;
      case "paymentAgencyList":
        formData.value.paymentAgencyShortName = value;
        break;
    }
    closePicker(); // 关闭选择器
  };

  /**
   * 拉取停车记录
   * @param pageNo
   * @param pageSize
   */
  const queryList = async (pageNo : number, pageSize : number) => {
    let params = {
      page: pageNo,
      size: pageSize,
      carParkId: carParkId.value,
      numberPlate: numberPlate.value,
    };
    if (numberPlate.value === '') {
      delete params.numberPlate;
    }
    if(formData.value.minInTime !== null){
      params.minInTime = dayjs(formData.value.minInTime).valueOf();
    }
    if(formData.value.maxInTime !== null){
      params.maxInTime = dayjs(formData.value.maxInTime).valueOf();
    }
    if(formData.value.minOutTime !== null){
      params.minOutTime = dayjs(formData.value.minOutTime).valueOf();
    }
    if(formData.value.maxOutTime !== null){
      params.maxOutTime = dayjs(formData.value.maxOutTime).valueOf();
    }
    if(formData.value.inCheckPointId !== null){
      params.inCheckPointId = formData.value.inCheckPointId;
    }
    if(formData.value.outCheckPointId !== null){
      params.outCheckPointId = formData.value.outCheckPointId;
    }
    if(formData.value.carType !== null){
      params.carType = formData.value.carType;
    }
    if(formData.value.inReleaseType !== null){
      params.inReleaseType = formData.value.inReleaseType;
    }
    if(formData.value.outReleaseType !== null){
      params.outReleaseType = formData.value.outReleaseType;
    }
    if(formData.value.homeGroup !== null){
      params.homeGroup = formData.value.homeGroup;
    }
    if(formData.value.paymentAgencyShortName !== null){
      params.paymentAgencyShortName = formData.value.paymentAgencyShortName;
    }
    const _dataList = await CfCarParkUtil.getCarParkUseLogListByQuery(params);
    if (_dataList.code == 10002) {
      dataList.value = _dataList.data;
      for (const i of _dataList.data) {
        i.newCarType = getCarTypeName(i.carType) || '-';
        i.newInTime = parseTime(i.inTime, '{m}-{d} {h}:{i}:{s}') || '-';
        i.newOutTime = parseTime(i.outTime, '{m}-{d} {h}:{i}:{s}') || '-';
        i.newPayTime = parseTime(i.payTime, '{m}-{d} {h}:{i}:{s}') || '-';
        i.parkingDuration = (i.inTime && i.outTime) ? timeFn(Number(i.inTime), Number(i.outTime)) : '-';
        for (const j of releaseTypeArr) {
          if (i.inReleaseType == j.value) {
            i.newInReleaseType = j.label;
          }
          if (i.outReleaseType == j.value) {
            i.newOutReleaseType = j.label;
          }
        }
        for (const j of paymentAgencyList.value) {
          if (i.paymentAgencyShortName == j.paymentAgencyName) {
            i.paymentAgencyShortNameTitle = j.name;
            break;
          }
        }
      }
    } else {
      dataList.value = [];
    }
    paging.value.complete(dataList.value);
  };

  /**
   * 拉取车辆类型
   */
  const getCarTypeList = async () => {
    const _carTypeList = await CfCarParkUtil.getCarTypeListByQuery({
      page: 1,
      size: 100
    });
    if (_carTypeList.code == 10002) {
      carTypeList.value = _carTypeList.data;
      for (const i of _carTypeList.data) {
        selectOptions.value.carTypeLabel[i.flagKey] = i.name;
        selectOptions.value.dict.carTypeList.push({
          label: i.name,
          text: i.name,
          value: i.flagKey
        });
      }
    } else {
      carTypeList.value = [];
    }
  };

  /**
   * 拉取支付方式
   */
  const getPaymentAgencyList = async () => {
    const _paymentAgencyList = await CfPayUtil.getPaymentAgencyListByQuery({
      page: 1,
      size: 200
    })
    if (_paymentAgencyList.code == 10002) {
      paymentAgencyList.value = _paymentAgencyList.data;
      for (const i of _paymentAgencyList.data) {
        selectOptions.value.paymentAgencyLabel[i.paymentAgencyName] = i.name;
        selectOptions.value.dict.paymentAgencyList.push({
          label: i.name,
          text: i.name,
          value: i.paymentAgencyName
        });
      }
    } else {
      paymentAgencyList.value = [];
    }
  }
  /**
   * 拉取出入口通道
   */
  const getCheckPointList = async () => {
    const _checkPointList = await CfIOTUtil.getCheckPointListByQuery({
      page: 1,
      size: 200,
      areaId: carParkId.value
    })
    if (_checkPointList.code == 10002) {
      for (const i of _checkPointList.data) {
        selectOptions.value.checkPointLabel[i.id] = i.name;
        if(i.features==='in'){
          selectOptions.value.dict.inCheckPointList.push({
            label: i.name,
            text: i.name,
            value: i.id
          });
        }else{
          selectOptions.value.dict.outCheckPointList.push({
            label: i.name,
            text: i.name,
            value: i.id
          });
        }
      }
    } else {
      paymentAgencyList.value = [];
    }
  }

  /**
   * 根据车辆类型key获取名称
   * @param key
   */
  const getCarTypeName = (key : string) => {
    // @ts-ignore
    const findRes : any = carTypeList.value.find((i) => i.flagKey === key);
    return findRes?.name;
  };
  onMounted(() => { });
  onLoad((params) => {
    getCarTypeList();
    getPaymentAgencyList();
    if (params != undefined) {
      carParkId.value = params.id;
      getCheckPointList();
    }
  });
</script>

<style scoped>
/* 样式 */
</style>
